package com.czl.module_user.viewmodel

import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.binding.command.BindingConsumer
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.ImgRspBean
import com.czl.base.data.bean.RoomBean
import com.czl.base.data.bean.UserDetailBean
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper

/**
 *
 * @Description:
 * @Author: XCH
 * @CreateDate: 2022/1/7 8:39
 */
class AddPeopleViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var personTypes = arrayOf("家庭成员", "租客", "朋友")
    var personGenders = arrayOf("男", "女")

    var peopleId = ""
    var peopleFrom = -1
    var roomList: List<RoomBean>? = null
    var houseNo = ""
    val houseName = ObservableField("")
    val idCardPhotoUrl = ObservableField("")
    val idCardBackPhotoUrl = ObservableField("")
    val personTypeName = ObservableField("")
    var personType = ""
    val idCard = ObservableField("")
    val phone = ObservableField("")
    var gender = ObservableInt(0)
    var applyStatus = ObservableInt(0)
    val name = ObservableField("")
    val remark = ObservableField("")
    val btnText = ObservableField("重新保存")
    var id = ""

    val uc = UiChangeEvent()

    class UiChangeEvent {
        val saveCompleteEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val choiceGenderEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val choicePersonTypeEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val choiceHouseEvent: SingleLiveEvent<List<RoomBean>> = SingleLiveEvent()
        val deleteSuccessEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val deleteEvent: SingleLiveEvent<String> = SingleLiveEvent()
        val choiceImgEvent: SingleLiveEvent<Int> = SingleLiveEvent()
    }

    val onImageClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceImgEvent.postValue(IMG_BEFORE)
    })
    val onBackImageClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceImgEvent.postValue(IMG_BACK)
    })

    val onGenderClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceGenderEvent.call()
    })
    val onPersonTypeClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choicePersonTypeEvent.call()
    })
    val onHouseClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceHouseEvent.postValue(roomList)
    })
    val onIdCardChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        idCard.set(it)
    })
    val onNameChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        name.set(it)
    })
    val onPhoneChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        phone.set(it)
    })
    val onAddPeopleClick: BindingCommand<Void> = BindingCommand(BindingAction {
        //0：保存；1：重新添加；其它：保存
        when (peopleFrom) {
            FROM_ADD -> addPeople()
            FROM_EDIT -> updatePeople()
        }
    })

    private fun addPeople() {
        model.addPeople(
            mapOf(
                "applyStatus" to "1",
                "areaId" to model.getAreaId(),
                "gender" to gender.get().toString(),
                "idCard" to idCard.get().orEmpty(),
                "name" to name.get().orEmpty(),
                "idCardPhotoUrl" to idCardPhotoUrl.get().orEmpty(),
                "idCardBackPhotoUrl" to idCardBackPhotoUrl.get().orEmpty(),
                "personType" to personType,
                "houseId" to houseNo,
                "houseCode" to houseName.get().orEmpty(),
                "phone" to phone.get().orEmpty(),
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.code == 200) {
                        uc.saveCompleteEvent.call()
                        showSuccessToast(t.msg)
                    } else {
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    showErrorToast(msg)
                }

            })
    }

    private fun updatePeople() {
        model.updatePeople(
            mapOf(
                "id" to id,
                "applyStatus" to "1",
                "areaId" to model.getAreaId(),
                "gender" to gender.get().toString(),
                "idCard" to idCard.get().orEmpty(),
                "name" to name.get().orEmpty(),
                "personType" to personType,
                "houseId" to houseNo,
                "houseCode" to houseName.get().orEmpty(),
                "phone" to phone.get().orEmpty(),
                "idCardPhotoUrl" to idCardPhotoUrl.get().orEmpty(),
                "idCardBackPhotoUrl" to idCardBackPhotoUrl.get().orEmpty(),
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.code == 200) {
                        uc.saveCompleteEvent.call()
                        showSuccessToast(t.msg)
                    } else {
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    showErrorToast(msg)
                }

            })
    }

    fun getUserRooms() {
        model.getUserRooms(model.getLoginPhone().toString(), model.getAreaId())
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(
                object : ApiSubscriberHelper<BaseBean<List<RoomBean>>>() {
                    override fun onResult(t: BaseBean<List<RoomBean>>) {
                        if (t.code == 200) {
                            roomList = t.data
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        showErrorToast(msg)
                    }

                }
            )
    }

    fun getUserDetail() {
        model.getApplyDetail(peopleId).compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(
                object : ApiSubscriberHelper<BaseBean<UserDetailBean>>(loadService) {
                    override fun onResult(t: BaseBean<UserDetailBean>) {
                        dismissLoading()
                        if (t.code == 200) {
                            t.data?.let {
                                id = it.id
                                name.set(it.name)
                                phone.set(it.phone)
                                idCard.set(it.idCard)
                                it.houseName?.let {
                                    houseName.set(it)
                                }
                                it.houseCode?.let {
                                    houseName.set(it)
                                }
                                remark.set(it.remark)
                                houseNo = it.houseId
                                idCardPhotoUrl.set(it.idCardPhotoUrl)
                                idCardBackPhotoUrl.set(it.idCardBackPhotoUrl)
                                applyStatus.set(it.applyStatus)
                                gender.set(it.gender)
                                it.personType?.let {
                                    if (it == 0 || it == 1) return@let
                                    personType = it.toString()
                                    personTypeName.set(personTypes[it - 2])
                                }
                            }
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        showErrorToast(msg)
                        dismissLoading()
                    }

                }
            )
    }

    fun deleteHouseUser(id: String) {
        model.deleteHouseUser(id)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.code == 200) {
                        uc.deleteSuccessEvent.call()
                        showSuccessToast(t.msg)
                    } else {
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    showErrorToast(msg)
                }
            })
    }

    fun uploadHeadImg(imgSrc: String, type: Int) {
        model.apply {
            uploadHeadImg("user", imgSrc, "")
                .compose(RxThreadHelper.rxSchedulerHelper(this@AddPeopleViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ImgRspBean>>() {
                    override fun onResult(t: BaseBean<ImgRspBean>) {
                        dismissLoading()
                        if (t.data == null) return
                        if (t.code == 200) {
                            when (type) {
                                IMG_BEFORE -> idCardPhotoUrl.set(t.data?.url)
                                IMG_BACK -> idCardBackPhotoUrl.set(t.data?.url)
                            }
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }
    }

    companion object {
        const val IMG_BEFORE = 101
        const val IMG_BACK = 100
        const val FROM_ADD = 102
        const val FROM_EDIT = 103
    }

}